﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class FBOFBSReturnsInterfaceBusiness_2 : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public FBOFBSReturnsInterfaceBusiness_2()
        {
            this.InterfaceName = "FBO/FBS商品退货_店铺2";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();
            

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置


                //获取源数据
                OZ_FBOFBSReturnsInterfaceBusiness_2 OZ_FBOFBSReturns = new OZ_FBOFBSReturnsInterfaceBusiness_2();
                List<FBOFBSReturns> sourceData = await OZ_FBOFBSReturns.QueryAsync<FBOFBSReturns>(OZ_FBOFBSReturns.OZ_Query, SqlDb);

                foreach (var item1 in sourceData)
                {
                    //退货所在仓库信息
                    item1.place_id = item1.place.id;
                    item1.place_name = item1.place.name;
                    item1.place_address = item1.place.address;
                    //退货运往仓库信息
                    item1.target_place_id = item1.target_place.id;
                    item1.target_place_name = item1.target_place.name;
                    item1.target_place_address = item1.target_place.address;
                    //库存信息
                    item1.sum_price = item1.storage.sum.price;
                    item1.sum_currency_code = item1.storage.sum.currency_code;
                    item1.tariffication_first_date = item1.storage.tariffication_first_date;
                    item1.tariffication_start_date = item1.storage.tariffication_start_date;
                    item1.arrived_moment = item1.storage.arrived_moment;
                    item1.days = item1.storage.days;
                    item1.utilization_sum_price = item1.storage.utilization_sum.price;
                    item1.utilization_sum_currency_code = item1.storage.utilization_sum.currency_code;
                    item1.utilization_forecast_date = item1.storage.utilization_forecast_date;
                    //产品信息
                    item1.sku = item1.product.sku;
                    item1.offer_id = item1.product.offer_id;
                    item1.name = item1.product.name;
                    item1.price_currency_code = item1.product.price.currency_code;
                    item1.price = item1.product.price.price;
                    item1.price_without_commission_currency_code = item1.product.price_without_commission.currency_code;
                    item1.price_without_commission = item1.product.price_without_commission.price;
                    item1.commission_percent = item1.product.commission_percent;
                    item1.commission_currency_code = item1.product.commission.currency_code;
                    item1.commission = item1.product.commission.price;
                    item1.quantity = item1.product.quantity;
                    //退货信息
                    item1.technical_return_moment = item1.logistic.technical_return_moment;
                    item1.final_moment = item1.logistic.final_moment;
                    item1.cancelled_with_compensation_moment = item1.logistic.cancelled_with_compensation_moment;
                    item1.return_date = item1.logistic.return_date;
                    item1.barcode = item1.logistic.barcode;

                    //退货状态信息
                    item1.status_id = item1.visual.status.id;
                    item1.status_display_name = item1.visual.status.display_name;
                    item1.status_sys_name = item1.visual.status.sys_name;
                    item1.change_moment = item1.visual.change_moment;

                    //其他信息
                    item1.is_opened = item1.additional_info.is_opened;
                    item1.is_super_econom = item1.additional_info.is_super_econom;
                }




                //获取目标数据
                List<FBOFBSReturns> targetData = new List<FBOFBSReturns>();//目标据集合
                var fDate = sourceData.OrderBy(x => x.return_date.ToDateTime()).First().return_date.ToDateTime().ToString("yyyy-MM-dd");
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d798f2cd44971bbfbd8268", DataType = 15, SpliceType = 1, FilterType = 14, Value = fDate }//FDATE字段过滤日开
            );
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "67d79a51cd44971bbfbda576", DataType = 2, SpliceType = 1, FilterType = 2, Value = sourceData[0].company_id }//店铺查询条件
            );
                targetData = await QueryAsync<FBOFBSReturns>(queryOption, tableField, SqlDb);
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    //#region
                    List<FBOFBSReturns> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<FBOFBSReturns>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    //#endregion

                    //新增
                    #region
                    List<FBOFBSReturns> insertItem = sourceData.Except(targetData, new ComparerFromKey<FBOFBSReturns>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<FBOFBSReturns> deleteItem = targetData.Except(sourceData, new ComparerFromKey<FBOFBSReturns>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion

                    if (sourceData.Count > 0)
                    {
                        //同步数据库
                        SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                        sqlDBInterface.ExecuteInterface<FBOFBSReturns>(targetData, "SD_OZ_FBOFBSReturns", $"WHERE return_date >='{fDate}' AND company_id ='{sourceData[0].company_id}'");
                    }
                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
